package com.i2863.receipt.service.impl;

import com.i2863.receipt.dao.PrizeRepository;
import com.i2863.receipt.entity.Prize;
import com.i2863.receipt.service.PrizeService;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/6/8.
 */
@Service
public class PrizeServiceImpl implements PrizeService{

    @Resource
    private PrizeRepository prizeRepository;


    @Override
    public Prize findOne(Integer id) {
        return prizeRepository.findOne(id);
    }

    @Override
    public void add(Prize prize) {
        prizeRepository.save(prize);
    }

    @Override
    public void del(Integer id) {
        prizeRepository.delete(id);
    }

    @Override
    public void update(Prize prize) {
        prizeRepository.saveAndFlush(prize);
    }

    @Override
    public List<Prize> findBySiteId(final Integer siteId) {
        Specification<Prize> specification = new Specification<Prize>() {
            @Override
            public Predicate toPredicate(Root<Prize> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();

                Predicate eqSiteId = cb.equal(root.get("site").get("id").as(Integer.class),siteId);
                predicates.add(eqSiteId);

                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return prizeRepository.findAll(specification);
    }

    @Override
    public Integer countLevelPrizeBySiteId(Integer level, Integer siteId) {
        return prizeRepository.countLevelPrizeBySiteId(level,siteId);
    }

    @Override
    public Integer sumBySiteIdAndLevel(Integer siteId, Integer level,Integer prizeRange) {
        return prizeRepository.sumBySiteIdAndLevelAndPrizeRange(siteId,level,prizeRange);
    }

    @Override
    public List<Prize> findBySiteIdAndPrizeRangeAndLevel(Integer siteId,Integer  prizeRange,Integer level){
        return prizeRepository.findBySiteIdAndPrizeRangeAndLevel(siteId,prizeRange,level);
    }

    @Override
    public List<Prize> findBySiteIdAndPrizeRange(Integer siteId,Integer  prizeRange){
        return prizeRepository.findBySiteIdAndPrizeRange(siteId,prizeRange);
    }

    @Override
    public List<Prize> groupPrizeByLevel(Integer siteId) {
        return prizeRepository.groupByLevel(siteId);
    }
}
